$(document).ready(function() {
	initialize();

	/*$("#buscar").click(function() {

	 //deleteOverlays();
	 });*/
});
var arrayMarker = new Array();
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var infowindows=null;
function initialize() {
	directionsDisplay = new google.maps.DirectionsRenderer();
	var chicago = new google.maps.LatLng(41.669, 1.516);
	var myOptions = {
		zoom : 10,
		mapTypeId : google.maps.MapTypeId.ROADMAP,
		center : chicago
	}
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	usuariMaps();

	//fem autocompletat
	var inputOrigen = document.getElementById('origen');
	var inputDesti = document.getElementById('desti');
	var options = {
		bounds : chicago,
		types : ['geocode']
	};
	autocompleteOrigen = new google.maps.places.Autocomplete(inputOrigen, options);
	$('#desti').focus(function() {
		var optionsDesti = {
			bounds : new google.maps.LatLng(41.670, 1.516),
			types : ['geocode']
		};

		autocompleteDesti = new google.maps.places.Autocomplete(inputDesti, optionsDesti);
	});
  infowindow = new google.maps.InfoWindow();
  
}

//calcula la ruta que s'indica en els textbox
function calcRoute(origen, desti) {
	var adresa = new Array;

	var request = {
		origin : origen,
		destination : desti,
		//unitSystem: google.maps.DirectionsUnitSystem["METRIC"],

		travelMode : google.maps.DirectionsTravelMode.DRIVING
	};
	directionsService.route(request, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			var mystr = "";
			var auxO;
			var auxD;

			for (var i in response.routes) {
				var mylegs = response.routes[i].legs;
				for (var j in mylegs) {
					mystr += mylegs[j].distance.text;
					mystr += " " + mylegs[j].duration.text + " <br/>";
					mystr += " origen " + mylegs[j].start_location + " <br/>";
					auxO = mylegs[j].start_location;
					mystr += " desti " + mylegs[j].end_location + " <br/>";
					auxD = mylegs[j].end_location;
					adresa[0] = mylegs[j].start_address;
					adresa[1] = mylegs[j].end_address;
				}
				mystr += "<br/>";
				$("#map_Distance").html(mystr);
			}
			directionsDisplay.setDirections(response);
			directionsDisplay.setMap(map);
			//directionsDisplay.setPanel($("#map_Ruta").get(0));
			//directionsDisplay.setPanel($("#map_Ruta"));
			//deleteOverlays();
			retornar(auxO, auxD);

			deleteOverlays();
		}
	});

}

//colocar els resultats de busqueda simple en el div corresponent
function buscarUsuari(aux) {

	$.post("resultatBuscar.php", {
		buscar : aux
	}, function(data) {

		$("#resultatCerca").html(data);
		$('#viatgesPublicats').hide();

	});
}

//mostra punts d'origen dels usuaris
function usuariMaps() {

	$.post('mostraCoordUsuaris.php', function(data) {
		var icon = "./images/coche.png";
		var cad = jQuery.parseJSON(data);
		var beachMarker;
		///alert(cad1.length);
		for (var i = 0; i < cad.length; i++) {
			///alert(i);
			var myLatLng = new google.maps.LatLng(cad[i].latO, cad[i].lonO);
			beachMarker = new google.maps.Marker({
				position : myLatLng,
				map : map,
				icon : icon,
				title : cad[i].usuari,
				html : '<div id="content">'+'<h3>'+
        'Usuari: <id="usuari">'+ cad[i].usuari+'</h3>'+
    '<div id="informacio">'+
    '<a href="oferta_ruta.php?id='+cad[i].idRuta+'"><b>Origen:</b>' + cad[i].adresaO+', <b>Desti:</b>' +cad[i].adresaD+'</a></div>'+
    '</div>'
    
   
    //cad[i].adresaO + ", " + cad[i].adresaD
			});
			google.maps.event.addListener(beachMarker, "click", function() {
				alert(this.html);
				infowindow.setContent(this.html);
				infowindow.open(map, this);
			});
			arrayMarker.push(beachMarker);
		}

	});

}

//esborra els punts(overlays)
function deleteOverlays() {
	if (arrayMarker) {
		for (i in arrayMarker) {
			arrayMarker[i].setMap(null);
		}
		arrayMarker.length = 0;
	}
}

//envia dades a php per calcular la distancia entre dos punts
function retornar(auxO, auxD) {//FA LA CRIDA CAP AL PHP
	//alert(auxO+" "+auxD);
	var latO = auxO.lat();
	var lonO = auxO.lng();
	var latD = auxD.lat();
	var lonD = auxD.lng();
	var cad = new Array();

	var iconOrigen = "./images/origen.png";
	var iconDesti = "./images/desti.png";
	
	$.post("distanciaPunts.php", {
		nomLatO : latO,
		nomLonO : lonO,
		nomLatD : latD,
		nomLonD : lonD

	}, function(data) {

		var cad = jQuery.parseJSON(data);

		buscarUsuari(cad);
		for (var i = 0; i < cad.length; i++) {

			var myLatLngO = new google.maps.LatLng(cad[i].latO, cad[i].lonO);
			var xinxetaOrigen = new google.maps.Marker({
				position : myLatLngO,
				map : map,
				icon : iconOrigen,
				title : cad[i].usuari,
html : '<div id="content">'+
        '<h3 id="usuari">'+cad[i].usuari+'</h3>'+
    '<div id="informacio">'+
    '<a href="oferta_ruta.php?id='+cad[i].idRuta+'"><b>Origen:</b>' + cad[i].adresaO+', <b>Desti:</b>' +cad[i].adresaD+'</a></div>'+
    '</div>'
    
   
    
			});
			google.maps.event.addListener(xinxetaOrigen, "click", function() {
				
				infowindow.setContent(this.html);
				infowindow.open(map, this);
			});
			
			var myLatLngD = new google.maps.LatLng(cad[i].latD, cad[i].lonD);
			var xinxetaDesti = new google.maps.Marker({
				position : myLatLngD,
				map : map,
				icon : iconDesti,
				title : cad[i].usuari,
		html : '<div id="content">'+
        '<h3 id="usuari">'+cad[i].usuari+'</h3>'+
    '<div id="informacio">'+
    '<a href="oferta_ruta.php?id='+cad[i].idRuta+'"><b>Origen:</b>' + cad[i].adresaO+', <b>Desti:</b>' +cad[i].adresaD+'</a></div>'+
    '</div>'
    
   
    
			});
			google.maps.event.addListener(xinxetaDesti, "click", function() {
				
				infowindow.setContent(this.html);
				infowindow.open(map, this);
			});
			arrayMarker.push(xinxetaOrigen);
			arrayMarker.push(xinxetaDesti);
		}

	});
}